import path from 'path';
import { DataSource, getMetadataArgsStorage } from 'typeorm';
import { MysqlConnectionOptions } from 'typeorm/driver/mysql/MysqlConnectionOptions';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';

import { ConstantEnum } from '../enums';
import { getConfig, isDev } from '../utils';

const DB_DATA_SOURCE = (options?: Partial<MysqlConnectionOptions>) => {
  const { DB_CONFIG } = getConfig();
  const entities =
    options?.entities ||
    getMetadataArgsStorage().tables.map((tbl) => tbl.target);
  setTimeout(() => {
    console.log('实例列表 :>> ', entities);
  }, 100);
  return new DataSource({
    type: DB_CONFIG.type, // 数据库链接类型
    host: DB_CONFIG.host,
    port: DB_CONFIG.port,
    username: DB_CONFIG.username,
    password: DB_CONFIG.password,
    database: DB_CONFIG.database, // 后面改成 scid
    synchronize: DB_CONFIG.synchronize, // 是否开启同步数据表功能
    namingStrategy: new SnakeNamingStrategy(),
    entities: entities,
    logging: true,
    charset: 'utf8mb4',
    // timezone: '+08:00',
    migrations: options?.migrations || [],
    subscribers: [],
    // // @ts-expect-error 类型错误
    // keepConnectionAlive: true,
    // retryDelay: DB_CONFIG.retryDelay,
    // retryAttempts: DB_CONFIG.retryAttempts,
    // autoLoadEntities: DB_CONFIG.autoLoadEntities,
  });
};

// 数据库注入
export const DatabaseProviders = [
  {
    provide: ConstantEnum.DB_DATA_SOURCE,
    useFactory: () => {
      return DB_DATA_SOURCE().initialize();
    },
  },
];

export default DB_DATA_SOURCE({
  migrations: ['migrations/*.ts'],
  entities: [path.resolve(process.cwd(), '**/entities/*.entity{.js,.ts}')],
});
